<template>
  <div class="site-wrapper">
    <div class="header clearfix">
      <el-button size="small" type="primary" :disabled="isObserver" @click="createTask">新增</el-button>
      <el-button size="small" type="primary" :disabled="multipleSelection.length === 0 || isObserver" @click="delTask(false)">批量删除</el-button>
      <div class="filter" @click="showFilter = true;"><img src="../../../../assets/livolobim/filter.png" alt="">搜索</div>
      <div class="mask" v-if="showFilter" @click="showFilter = false;"></div>
      <div class="filter-wrapper" v-if="showFilter">
        <span class="filter-arrow"></span>
        <span class="filter-white"></span>
        <div class="filter-header">搜索</div>
        <el-form :model="filterData" style="padding: 0 16px;" label-width="110px">
          <el-form-item label="公司名称">
            <el-input v-model="filterData.name" placeholder="中文名称和英文名称"></el-input>
          </el-form-item>
          <el-form-item label="所属国家">
            <el-select :filterable="true" style="width: 100%;" v-model="filterData.countryCode" placeholder="请选择国家地区">
              <el-option v-for="item in gjdq" :key="item.code" :label="item.name + '(' + item.code + ')'" :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button style="float:right;margin-right: 16px;" size="small" type="primary" @click="searchItem(true)">确定</el-button>
          <el-button style="float:right;margin-right: 16px;" size="small" @click="resetFilter">重置</el-button>
        </div>
      </div>
    </div>
    <div class="data-wrapper">
      <el-table :height="tableHeight" :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55"></el-table-column>
        <el-table-column align="center" prop="name" label="公司名称" min-width="100"></el-table-column>
        <el-table-column align="center" prop="countryName" label="所属国家" min-width="100"></el-table-column>
        <el-table-column align="center" prop="address" label="公司地址" min-width="100"></el-table-column>
        <el-table-column align="center" prop="profession" label="所属行业" min-width="100"></el-table-column>
        <el-table-column align="center" prop="webSite" label="公司网站" min-width="100"></el-table-column>
        <el-table-column label="操作" min-width="180" align="center">
          <template slot-scope="scope">
            <el-button @click="openEdit(scope.row, true)" type="text" size="small">查看</el-button>
            <el-button v-if="!isObserver" @click="openEdit(scope.row, false)" type="text" size="small">编辑</el-button>
            <el-button v-if="!isObserver" @click="delTask(scope.row.id)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style=""
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="page"
        :page-sizes="[15, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      <el-dialog width="1000px" :visible.sync="showForm" :show-close="true">
        <div slot="title">
          <h2 style="text-align:center;margin-bottom:0;">{{form.id? isCheck? '查看': '编辑': '创建'}}公司</h2>
        </div>
        <div class="form-wrapper" style="padding: 0 20px;">
          <el-form ref="form" :model="form" label-width="140px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="公司名称：">
                  <span slot="label">公司名称<span style="color: red;">*</span>：</span>
                  <el-input :disabled="isCheck" v-model="form.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="英文名称：">
                  <el-input :disabled="isCheck" v-model="form.enName"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="公司地址：">
                  <el-input :disabled="isCheck" v-model="form.address"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="公司网站：">
                  <el-input :disabled="isCheck" v-model="form.webSite"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
             <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="所属行业：">
                  <el-input :disabled="isCheck" v-model="form.profession"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="经营范围：">
                  <el-input :disabled="isCheck" v-model="form.scope"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
             <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="国家地区：">
                  <span slot="label">国家地区<span style="color: red;">*</span>：</span>
                  <el-select :disabled="isCheck" :filterable="true" style="width: 100%;" v-model="form.countryCode" placeholder="请选择国家地区">
                    <el-option v-for="item in gjdq" :key="item.code" :label="item.name + '(' + item.code + ')'" :value="item.code"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item style="font-weight: bold;" label="联系人：">
                  <el-row v-for="(contact,idx) in form.customers" :gutter="24" :key="idx" :style="{'margin-top': idx > 0 ? '5px': '0px'}">
                    <el-col :span="22" :style="{'margin-left': idx === 0? '0': '12px'}" style="padding-left: 0;">
                      <el-select
                        style="width: 100%;"
                        v-model="contact.id"
                        filterable
                        remote
                        :disabled="isCheck"
                        reserve-keyword
                        placeholder="请输入客户名称、编号(最少输入2个字母)"
                        :remote-method="remoteMethod"
                        @change="select(contact)"
                        :loading="loading">
                        <el-option
                          v-for="item in custormerList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                        </el-option>
                      </el-select>
                    </el-col>
                    <i v-if="(form.customers.length -1) === idx && !isCheck" @click="addItem(idx)" class="el-icon-circle-plus" style="cursor:pointer;"></i>
                    <i v-if="(form.customers.length -1) !== idx && !isCheck" @click="removeItem(idx)" class="el-icon-remove" style="cursor:pointer;"></i>
                  </el-row>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button style="float:right;" size="small" @click="showForm = false">关闭</el-button>
              <el-button v-if="!isCheck" style="float:right;margin-right: 10px;" size="small" type="primary" @click="saveForm">保存</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import dingMixin from "@/mixins/ding";
import formUtil from "@/utils/formUtil";
import {dateUtil} from '@/utils/dateUtil'

export default {
  data() {
    return {
      gjdq: [],
      showFilter: false,
      loading:false,
      showForm: false,
      tableHeight: window.tableHeight,
      tableData: [],
      page:1,
      pageSize: 15,
      totalPage: 1,
      form: {
        name: '',
        enName: '',
        address: '',
        webSite: '',
        profession: '',
        scope: '',
        countryCode: '',
        countryName: '',
        customers: []
      },
      formVerify: {
        name: '请输入公司名称',
        countryCode: '请选择所属国家'
      },
      custormerList: [],
      filterData: {
        name: '',
        countryCode: ''
      },
      multipleSelection: [],
      isCheck: false,
    }
  },
  mixins: [dingMixin],
  computed: {
    isObserver() {
      return this.userInfo.roleIdList && this.userInfo.roleIdList.includes('1289086254290432001')
    }
  },
  async mounted() {
    this.$nextTick(() => {
      this.tableHeight = document.documentElement['clientHeight'] - 170;
    })
    window.onresize = () => {
      this.tableHeight = document.documentElement['clientHeight'] - 170
    }
    this.searchItem(true);
    this.gjdq = await this.$httpN.postQ('mpb/market/listCountry')
  },
  methods: {
    resetFilter() {
      this.filterData = {
        name: '',
        countryCode: ''
      };
    },
    createTask() {
      this.showForm = true;
      this.isCheck = false;
      formUtil.resetData(this.form);
      this.form.customers.push({
        id: '',
        name: ''
      })
    },
    delTask(id) {
      let ids = id ? [id]: this.multipleSelection.map(item => item.id);
      formUtil.submitConfirm('您确定要删除公司吗？', async ()=> {
        if(!await this.$httpN.postB('crm/company/delete', ids, false)) return;
        formUtil.submitSuccess('删除成功');
        this.searchItem(true);
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async openEdit(target, isCheck) {
      this.form = await this.$httpN.postQ('crm/company/info', {id: target.id})
      if(this.form.customers.length > 0) {
        this.custormerList = formUtil.deepCopy(this.form.customers);
      }else {
        this.form.customers.push({
          id: '',
          name: ''
        })
      }
      this.showForm = true;
      this.isCheck = isCheck;
    },
    async saveForm() {
      this.gjdq.forEach((item) => {
        if(item.code === this.form.countryCode) {
          this.form.countryName = item.name;
        };
      })
      if(!formUtil.verifyData(this.form, this.formVerify)) return;
      if(!await this.$httpN.postB('crm/company/save', this.form)) return;
      formUtil.submitSuccess('成功');
      this.showForm = false;
      this.searchItem(true);
    },
    async remoteMethod(query) {
      if (query !== '' && query.length >= 2) {
        this.loading = true;
        this.custormerList = await this.$httpN.postQ('mpb/customer/getByName', {name: query});
        this.loading = false;
      } else {
        this.custormerList = [];
      }
    },
    sizeChangeHandle(limit) {
      this.pageSize = limit;
      this.searchItem(true);
    },
    currentChangeHandle(page) {
      this.page = page;
      this.searchItem();
    },
    async searchItem(init) {
      if(init) this.page = 1;
      let data = await this.$httpN.postB('crm/company/list',{
        countryCode: this.filterData.countryCode,
        name: this.filterData.name,
        page: this.page,
        limit: this.pageSize,
      })
      this.tableData = data.list;
      this.totalPage = data.totalCount
    },
    removeItem(idx) {
      this.form.customers.splice(idx,1) 
    },
    addItem(idx) {
      this.form.customers.splice(idx+1, 0, {
        id: '',
        name: ''
      }) 
    },
    select(current) {
      this.custormerList.forEach((item) => {
        if(item.id === current.id) {
          current.name = item.name;
        };
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .header{
    position: relative;
    padding: 10px 0 0 20px ;
    .filter{
      cursor: pointer;
      float: right;
      margin-right: 30px;
      line-height: 30px;
      img{
        width: 16px;
        margin-right: 3px;
      }
    }
    .mask{
      position: fixed;
      height: 100vh;
      width: 100%;
      top: 0;
      right: 0;
      z-index: 3;
    }
    .filter-wrapper{
      position: absolute;
      width: 455px;
      padding-bottom: 20px;
      background: white;
      top: 48px;
      right: 20px;
      z-index: 99;
      border-radius: 5px;
      box-shadow: 0 0 3px black;
      .filter-header{
        line-height: 40px;
        padding-left: 16px;
        border-bottom: 1px solid #DDD;
        margin-bottom: 20px;
      }
      .filter-arrow{
        width:12px;
        height:12px;
        position: absolute;
        top: -7px;
        right: 20px;
        box-shadow: 0 0 3px black;
        transform: rotate(45deg);
      }
      .filter-white{
        width:18px;
        height:18px;
        position: absolute;
        top: -2px;
        right: 17px;
        border-radius: 3px;
        background: white;
      }
    }
  }
  .data-wrapper{
    padding: 0 20px;
    margin-top: 10px;
  }
  .select-btn{
    display: inline-block;
    font-weight: normal;
    margin-right: 5px;
    width: 80px;
    height: 28px;
    border-radius: 30px;
    background: #FAFAFA;
    border: 1px solid #ECECEC;
    position: relative;
    line-height: 28px;
    color: #7982A7;
    font-size: 12px;
    text-align: center;
    position: relative;
    cursor: pointer;
    .del{
      position: absolute;
      top:0;
      left: 0;
      width: 100%;
      height: 100%;
      border-radius: 30px;
      color: white;
      text-align: center;
      background:rgba(130, 130, 130, 0.9);
      display: none;
    }
    &:hover{
      .del{
        display: block;
      }
    }
  }
  .fileitem{
    line-height: 32px;
    margin-bottom: 5px;
    background: #F5F5F5;
    width: 474px;
    padding-left:15px;
    font-size: 12px;
    .uploadtip{
      float:right;
      margin-right: 20px;
      cursor: pointer;
    }
  }
  .addfilebtn{
    cursor: pointer;
    color: #909399;
    display: block;
    font-weight: normal;
  }
</style>